package com.gitee.lw114514.webapp_memorandium.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import com.gitee.lw114514.webapp_memorandium.service.DelService.DelService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@CrossOrigin(origins = {"http://localhost:5500", "http://127.0.0.1:5500"}, allowCredentials = "true", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
public class DelTaskController {
    //1.引入service层
    @Autowired
    private DelService deleteService;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class DeleteRequest {
        private Integer task_id;
        private Boolean task_status;
    }

    @RequestMapping(value = "/api/del_task", method = RequestMethod.DELETE)
    public Boolean delTask(@RequestBody DeleteRequest request) {
        System.out.println("删除任务：" + request);

        Integer taskId = request.getTask_id();
        Boolean taskStatus = request.getTask_status();

        System.out.println("删除任务：" + taskId + "任务状态：" + taskStatus);
        //2.处理请求
        //3.调用service层，获取数据
        Boolean result = deleteService.deleteTask(taskId, taskStatus);
        //4.返回删除结果（成功、失败）
        return result;
    }

    @RequestMapping(value = "/api/del_task/debug", method = RequestMethod.DELETE)
    public ResponseEntity<String> debugDelTaskData(@RequestBody String rawRequestData, HttpServletRequest request) {
        System.out.println("=== 原始请求数据拦截 ===");
        System.out.println("请求URL: " + request.getRequestURL());
        System.out.println("请求方法: " + request.getMethod());
        System.out.println("Content-Type: " + request.getContentType());
        System.out.println("原始请求体数据: " + rawRequestData);

        // 尝试解析JSON
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(rawRequestData);
            System.out.println("解析后的JSON结构: " + jsonNode.toPrettyString());

            // 检查关键字段
            JsonNode taskIdNode = jsonNode.get("task_id");
            JsonNode taskStatusNode = jsonNode.get("task_status");

            System.out.println("taskId字段: " + (taskIdNode != null ? taskIdNode.toString() : "null"));
            System.out.println("taskStatus字段: " + (taskStatusNode != null ? taskStatusNode.toString() : "null"));

        } catch (Exception e) {
            System.out.println("JSON解析失败: " + e.getMessage());
        }

        return ResponseEntity.ok("数据拦截完成，详情请查看控制台日志");
    }

}


